package com.sky.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.sky.properties.AliOSSProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
@Component
public class AliOSSUtils {
    @Autowired
    private AliOSSProperties aliOSSProperties;

    public String uploadFile(MultipartFile image) throws IOException {
            String endpoint = aliOSSProperties.getEndpoint();
            //AccessKeySecret 是用户用于加密签名字符串
            String accessKeyId = aliOSSProperties.getAccessKeyId();
            // OSS 用来验证签名字符串的密钥，必须保密
            String accessKeySecret = aliOSSProperties.getAccessKeySecret();
            String bucketName = aliOSSProperties.getBucketName();
            InputStream inputStream = image.getInputStream();
            String originalFilename = image.getOriginalFilename();
            String fileName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId,accessKeySecret);
            ossClient.putObject(bucketName, fileName, inputStream);
            ossClient.shutdown();
            return "https://"+bucketName+"."+endpoint.split("//")[1]+"/"+fileName;
    }
}
